/*
 * main.cpp
 *
 *  Created on: 11-May-2011
 *      Author: tan-ce
 */


#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <cstring>
#include <signal.h>

#include "tcetools/socket.h"

#include "constants.h"
#include "webcmd.h"

using namespace std;
using namespace tcetools;

extern std::string baseurl;

void drop_root() {
	if (geteuid() == 0) { // Hmm.... we are root...
		uid_t real_id = getuid();

		if (real_id == 0) {
			cout << "We are root, and the real ID is also root. It is more "
					"secure to chown the binary to root, and flip the setuid "
					"bit. Then I can change uid to the real (unprivilaged) "
					"user." << endl;
		} else {
			cout << "Current effective user is root. Changing effective uid to "
					<< real_id << "." << endl;
			seteuid(real_id);
		}
	}
}

int main(int argc, char *argv[]) {
	cout << APP_NAME << endl;

    struct sigaction newact;
    newact.sa_handler = SIG_IGN;
    if (sigaction(SIGPIPE, &newact, NULL) == -1) {
        cout << "Warning: Could not ignore sigpipe" << endl;
    }

	if (argc > 1 && string(argv[1]).compare("--webcmd") == 0) {
		baseurl = "/";
		launch_webcmd(argc - 2, &argv[2]);
	} else if (argc > 3 &&
			string(argv[3]).compare("--webcmd") == 0 &&
			string(argv[1]).compare("--baseurl") == 0) {
		baseurl = argv[2];

		if (baseurl[baseurl.length() - 1] != '/') baseurl.append("/");

		launch_webcmd(argc - 4, &argv[4]);
	} else cout << "Please pass the webcmd parameter and optionally a baseurl";

	return 0;
}
